package com.ruoyi.book.service.impl;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.time.ZoneId;
import java.time.format.DateTimeFormatter;
import java.util.Date;
import java.util.List;
import java.time.LocalDateTime;


import com.ruoyi.book.domain.Bookinfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.ruoyi.book.mapper.BorrowinfoMapper;
import com.ruoyi.book.domain.Borrowinfo;
import com.ruoyi.book.service.IBorrowinfoService;

import javax.xml.crypto.Data;

/**
 * 借阅信息Service业务层处理
 *
 * @author ruoyi
 * @date 2025-02-26
 */
@Service
public class BorrowinfoServiceImpl implements IBorrowinfoService {
    @Autowired
    private BorrowinfoMapper borrowinfoMapper;

    /**
     * 查询借阅信息
     *
     * @param id 借阅信息主键
     * @return 借阅信息
     */
    @Override
    public Borrowinfo selectBorrowinfoById(Long id) {
        return borrowinfoMapper.selectBorrowinfoById(id);
    }

    /**
     * 查询借阅信息列表
     *
     * @param borrowinfo 借阅信息
     * @return 借阅信息
     */
    @Override
    public List<Borrowinfo> selectBorrowinfoList(Borrowinfo borrowinfo) {
        return borrowinfoMapper.selectBorrowinfoList(borrowinfo);
    }

    /**
     * 新增借阅信息
     *
     * @param borrowinfo 借阅信息
     * @return 结果
     */
    @Override
    public int insertBorrowinfo(Borrowinfo borrowinfo) {

        // 判断图书是否借完
        Bookinfo bookinfo = borrowinfoMapper.selectByBookid(borrowinfo.getBookid());
        if (bookinfo.getRemain() == 0){
            throw new RuntimeException("此书已借完");
        }

        // 借取成功数量-1
        borrowinfoMapper.selectByJian(borrowinfo.getBookid());


        // 获取当前日期时间
        LocalDateTime now = LocalDateTime.now();
        // 格式化日期时间为字符串，格式为 yyyyMMddHHmmss
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyyMMddHHmmss");
        String borrowId = now.format(formatter);
        // 设置借阅号
        borrowinfo.setBorrowid(borrowId);

        return borrowinfoMapper.insertBorrowinfo(borrowinfo);
    }

    /**
     * 修改借阅信息
     *
     * @param borrowinfo 借阅信息
     * @return 结果
     */


    @Override
    public int updateBorrowinfo(Borrowinfo borrowinfo) {


        // 归还成功数量+1
        borrowinfoMapper.selectByjia(borrowinfo.getBookid());


        return borrowinfoMapper.updateBorrowinfo(borrowinfo);
    }


    /**
     * 批量删除借阅信息
     *
     * @param ids 需要删除的借阅信息主键
     * @return 结果
     */
    @Override
    public int deleteBorrowinfoByIds(Long[] ids) {
        return borrowinfoMapper.deleteBorrowinfoByIds(ids);
    }

    /**
     * 删除借阅信息信息
     *
     * @param id 借阅信息主键
     * @return 结果
     */
    @Override
    public int deleteBorrowinfoById(Long id) {
        return borrowinfoMapper.deleteBorrowinfoById(id);
    }
}
